package org.takeback.chat.service.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.takeback.chat.entity.PubUser;
import org.takeback.core.service.MyListServiceInt;
import org.takeback.mvc.listener.SessionListener;
import org.takeback.util.exception.CodedBaseRuntimeException;

@Service("onlineUserService")
public class OnlineUserService extends MyListServiceInt {
	@Transactional(readOnly = true)
	public Map<String, Object> list(Map<String, Object> req) {
		String entityName = (String) req.get(ENTITYNAME);
		if (StringUtils.isEmpty(entityName)) {
			throw new CodedBaseRuntimeException(404, "missing entityName");
		}
        int limit = (int) req.get(LIMIT);
        int page = (int) req.get(PAGE);

		Map<Integer, List<String>> users = SessionListener.getUsers();
		Set<Integer> keyset = users.keySet();
        Integer start = (page - 1) * limit;
        Integer end = start + limit;
		Iterator itr = keyset.iterator();
        Integer idx = -1;
		StringBuffer keys = new StringBuffer();
		while (itr.hasNext()) {
			Integer localInteger1 = idx;
			Integer localInteger2 = idx = Integer.valueOf(idx.intValue() + 1);
			if (idx.intValue() < start.intValue()) {
				itr.next();
			} else {
                keys.append(itr.next()).append(",");
                if (idx + 1 >= end) {
                    break;
                }
			}
		}
		HashMap result = new HashMap();
		if (keys.length() < 1) {
            result.put("totalSize", 0);
            result.put("body", new ArrayList());
            return result;
		}
		String key = keys.substring(0, keys.length() - 1);
		String hql = "from PubUser where id in(" + key + ")";
		List<PubUser> ls = this.dao.findByHql(hql);
		long count = users.size();
        result.put("totalSize", count);
        result.put("body", ls);
		return (Map<String, Object>) result;
	}
}
